package com.eascs.crm.nsEditDetail.controller;

import java.text.DecimalFormat;
import java.text.Format;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.eascs.admin.common.vo.ModelResult;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.crm.nsEditDetail.entity.CustomerBasicEntity;
import com.eascs.crm.nsEditDetail.service.CustomerInfoService;
import com.eascs.crm.nsEditDetail.vo.CustomerBasicVo;
import com.eascs.crm.nsEditDetail.vo.LoanBaseInfoVO;
import com.eascs.crm.nsEditDetail.vo.O2oLoanUserVo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;

@Controller
@RequestMapping("/customerInfo/rest")
public class CustomerInfoRestController extends BaseRestController {
	private final Logger logger = LoggerFactory.getLogger(CustomerInfoRestController.class);
	@Autowired
	private CustomerInfoService customerInfoService;
	
	@Value("${web.crm.url}")
	private String crmUrl;
	
	@Value("${web.homeUrl}")
	private String adminUrl;
	
	@RequestMapping(value = "/query-view")
	public HtmlRestResult queryIndex(String loanUserId,@RequestParam(required=false) String spouseId) {
		CustomerBasicVo customer = customerInfoService.queryCustomerById(loanUserId, spouseId);
		ViewContext.put("customer", customer);
		ViewContext.put("crmUrl", crmUrl);
		return new HtmlRestResult("/nsEditDetail/customer_basic_info_view");
	}
	
	@RequestMapping(value = "/query-update")
	public HtmlRestResult queryUpdate(String loanUserId,@RequestParam(required=false) String spouseId) {
		CustomerBasicVo customer = customerInfoService.queryCustomerById(loanUserId, spouseId);
		ViewContext.put("customer", customer);
		ViewContext.put("crmUrl", crmUrl);
		return HtmlRestResult.popHtmlFragment("/nsEditDetail/customer_basic_info_update");
		
	}

	
	@RequestMapping(value = "/query-spouse-view")
	public HtmlRestResult querySpouseIndex(String loanUserId,@RequestParam(required=false) String spouseId) {
		CustomerBasicVo customer = customerInfoService.queryCustomerById(loanUserId, spouseId);
		ViewContext.put("customer", customer);
		ViewContext.put("crmUrl", crmUrl);
		return new HtmlRestResult("/nsEditDetail/customer_spouse_info_view");
	}
	
	@RequestMapping(value = "/query-spouse-update")
	public HtmlRestResult querySpouseUpdate(String loanUserId,@RequestParam(required=false) String spouseId) {
		CustomerBasicVo customer = customerInfoService.queryCustomerById(loanUserId, spouseId);
		ViewContext.put("customer", customer);
		ViewContext.put("crmUrl", crmUrl);
		return HtmlRestResult.popHtmlFragment("/nsEditDetail/customer_spouse_info_update");
		
	}
	
	@RequestMapping(value = "/update")
	public BaseRestResult<String> updateIndex(CustomerBasicEntity entity, O2oLoanUserVo o2oLoanUserVo) {
//		if(StringUtil.isBlank(o2oLoanUserVo.getUserNamePinyin())){
//			 return BaseRestResult.warn("借款人/配偶姓名拼音不能为空");
//		}
		
		if(StringUtil.isBlank(o2oLoanUserVo.getUserPhone())){
			return BaseRestResult.warn("借款人/配偶联系电话不能为空");
		}
		if (!"1".equals(o2oLoanUserVo.getCustomerType())) {
			if(entity.getMarital_status()==2){
		    	 if(entity.getMarryDate()==null){
		    		 return BaseRestResult.warn("请选择结婚日期");
		    	 }
		    	
		      }
		      
		      if(entity.getMarital_status()==3){
		     	 if(entity.getDivorceDate()==null){
		     		 return BaseRestResult.warn("请选择离婚日期");
		     	 }
		     	
		       }
		}
		logger.info("输入借款人姓名拼音：【{}】", o2oLoanUserVo.getUserNamePinyin());
		ModelResult<CustomerBasicEntity> modelResult = customerInfoService.udpateEntity(entity, o2oLoanUserVo);
		if (!modelResult.isSuccess()) {
			 return BaseRestResult.warn("修改失败");
		}
		
		return BaseRestResult.info("修改成功").andRefresh();
	}

	@RequestMapping("/save")
	public BaseRestResult<String> saveInfoSave(CustomerBasicEntity entity) {
		ModelResult<CustomerBasicEntity> modelResult = customerInfoService.saveEntity(entity);
		if (!modelResult.isSuccess()) {
			 return BaseRestResult.info("新增失败");
		}
		return BaseRestResult.info("新增成功");
	}
	
	/**
	 * 查询 夫妻双方的贷款记录
	 * @param customer_id_number
	 * @param mate_id_number
	 * @return
	 */
	@RequestMapping("/loan_detail")
	public PaginationRestResult loan_detail(String customer_id_number, String mate_id_number,String flag) {
		String               o2ourl     = "/customerInfo/rest/loan_detail";
		LoanBaseInfoVO       vo         = new LoanBaseInfoVO();
		PageResult<Object[]> pageResult = new PageResult<Object[]>();
		String               id_numbers = customer_id_number;
		
		vo.setIdNumbers(id_numbers);
		if (!StringUtils.isEmpty(vo.getIdNumbers())) {
			pageResult = customerInfoService.findCustomerOrMateLoan(vo);
		}

		// 申请状态（新建：NEW,征信中：Z，征信完成：ZF，内审中：N，内审完成:NF，申报中：S，申报完成：SF,银行驳回：SN,已放款/审批通过：O，作废：T,还款完成：HN，代偿：DC，逾期：YQ）
		// #当申请状态为‘还款完成：HN’状态时，显示结清日期settle_date，否则为空
		String[] oatitles = {"贷款编号", "贷款类型", "借款人姓名","配偶姓名", "经办平台", "放款银行", "申请金额", "放款金额", "放款日期", "到期日期", "结清日期", "申请状态", "创建日期"};
		SelectDataOption[] selectDataOptions = { null, null, null, null, null,null, null, null, null, null, null, new SelectDataOption("SQZT"), null};
		o2ourl = UrlUtil.appendUrl(o2ourl, "idNumbers", vo.getIdNumbers());

		PaginationInfo paginationInfo = new PaginationInfo(pageResult, oatitles, o2ourl);
		if(!StringUtils.isEmpty(flag)){
			Button[]       titleButton    = new Button[]{ButtonHelper.createOpenButton(null, adminUrl + "/detail?billCode=")};
			paginationInfo.setTitleButtons(titleButton);
		}
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setRendTo("#oa_result");
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[]{null,null, null, null, null, null, new DecimalFormat(",##0.00"),
				new DecimalFormat(",##0.00"), null, null, null, null});
		ViewContext.put("vo", vo);
		ViewContext.put("paginationInfo", paginationInfo);
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}
	
}
